package com.sto.stoapp.scan;

import android.annotation.SuppressLint;
import android.content.Context;

import com.sto.stoapp.db.manager.ScanRuleDBManager;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ScanRuleManager {
	static ScanRuleManager mgr;

	static String waybillCodeRegular = "";
	static String carSealRegular = "";
	static String bagCodeRegular = "";
	static String specificRegular = "";
	static Context context;

	private ScanRuleManager(Context context) {
		this.context = context;
		refreshFromDB();
	}

	public static ScanRuleManager getInstance(Context context) {
		if (mgr == null) {
			mgr = new ScanRuleManager(context);
		}
		return mgr;
	}

	public String changeCodeType(String code) {
		if (isCarSealCode(code)) {
			return "40";
		} else if (isBagCode(code)) {
			return "20";
		} else if (isWaybillCode(code)) {
			return "10";
		}
		return "";
	}


	public void refreshFromDB() {
		waybillCodeRegular = getWaybillCodeRegular();
		carSealRegular = getCarSealRegular();
		bagCodeRegular = getBagCodeRegular();
		specificRegular = getSpecificRegular();
	}


	@SuppressLint("NewApi")
	public boolean isSpecificCode(String code) {
		if (specificRegular.isEmpty()) {
			specificRegular = getSpecificRegular();
		}
		return matching(code, specificRegular);
	}


	@SuppressLint("NewApi")
	public boolean isWaybillCode(String code) {
		if (waybillCodeRegular.isEmpty())
			waybillCodeRegular = getWaybillCodeRegular();
		return matching(code, waybillCodeRegular);
	}


	public boolean isCarSealCode(String code) {
		if (carSealRegular.isEmpty())
			carSealRegular = getCarSealRegular();
		return matching(code, carSealRegular);
	}


	public boolean isBagCode(String code) {
		if (bagCodeRegular.isEmpty())
			bagCodeRegular = getBagCodeRegular();
		return matching(code, bagCodeRegular);
	}

	private static boolean matching(String code, String regular) {
		boolean matching = false;
		try {
			Pattern p = Pattern.compile(regular);
			Matcher m = p.matcher(code);
			matching = m.matches();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return matching;
	}

	private static String getWaybillCodeRegular() {
		return ScanRuleDBManager.getInstance(context).getRegularByType(
				"CODE0001");
	}

	private static String getCarSealRegular() {
		return ScanRuleDBManager.getInstance(context).getRegularByType(
				"CODE0003");
	}

	private static String getBagCodeRegular() {
		return ScanRuleDBManager.getInstance(context).getRegularByType(
				"CODE0002");
	}

	private static String getSpecificRegular() {
		return ScanRuleDBManager.getInstance(context).getSpecificRegular();
	}

}
